﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Imports System.Data.Objects
Imports System.Text
Imports System.IO

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI


Partial Class Control_Contents_List
    Inherits System.Web.UI.UserControl
    Dim level As String = -1
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'xu ly jquery khi post back
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If

            getYear()
            getWeek()

            cboAction.Visible = HasPermission(Function_Name.Content, Session("RoleID"), 0, Audit_Type.Create)
            getStatus()
            getMenu()
            If Not String.IsNullOrEmpty(Request.QueryString("MenuId")) Then
                drlParent.SelectedValue = Request.QueryString("MenuId")
            End If
            BindToGrid(1, txtTitleFilter.Text.Trim(), drlType.SelectedValue, drlStatus.SelectedValue, txtNguoitao.Text.Trim, drlParent.SelectedValue, ddlSSMOriginal.SelectedValue, txtStartCreated.Text.Trim, ddlYear.SelectedValue, ddlWeek.SelectedValue, txtEndCreated.Text.Trim)
            If HasPermission(Function_Name.Content, Session("RoleID"), 0, Audit_Type.Delete) = True Then
                btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
            Else
                btnDelete.Enabled = False
            End If
            btnChange.Attributes.Add("onclick", "return confirmMultiChange('" & btnChange.ClientID & "');")
            btnSelectMenu.Attributes.Add("onclick", "return setChooseBranchNewsParentValue();")
        End If


    End Sub
    Protected Sub getMenu()
        drlParent.Items.Clear()
        Using data As New VSEntities
            Dim p As List(Of Menu) = (From q In data.Menus Select q).ToList
            drlParent.DataValueField = "MenuID"
            drlParent.DataTextField = "Title"

            ddlMenuChange.DataValueField = "MenuID"
            ddlMenuChange.DataTextField = "Title"

            RecursiveFillTree(p, 0)
            drlParent.Items.Insert(0, New ListItem("---Tất cả---", "0"))
            ddlMenuChange.Items.Insert(0, New ListItem("--- Chọn ---", "0"))
        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Menu), ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1

            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Using data As New VSEntities
            Dim dv As List(Of Menu) = (From q In data.Menus Where q.ParentId = parentID Select q).ToList
            Dim i As Integer

            If dv.Count > 0 Then
                For i = 0 To dv.Count - 1
                    Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).MenuId.ToString())
                    If Check_Selected(dv.Item(i).MenuId) = False Then
                        itm.Attributes.Add("class", "ItemDisabled")
                    Else
                        itm.Attributes.Add("class", "ItemActived")
                    End If

                    drlParent.Items.Add(itm)
                    ddlMenuChange.Items.Add(itm)
                    RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).MenuId.ToString()))
                Next
            End If
        End Using
        level -= 1
        'on the each function end level will decrement by 1
    End Sub

    Protected Sub getStatus()
        Using data As New VSEntities
            Dim p = (From q In data.Status Select q).ToList
            drlStatus.AppendDataBoundItems = True
            drlStatus.Items.Add(New ListItem("---Tất cả---", 0))
            drlStatus.DataValueField = "StatusId"
            drlStatus.DataTextField = "Title"
            drlStatus.DataSource = p
            drlStatus.DataBind()
            drlStatus.SelectedValue = 0
        End Using
    End Sub
    Protected Sub getYear()
        ddlYear.AppendDataBoundItems = True
        ddlYear.Items.Add(New ListItem("---Tất cả---", 0))
        ddlYear.DataSource = Enumerable.Range(2001, 15)
        ddlYear.DataBind()
        ddlYear.SelectedValue = 0 'Year(Now.Date)
    End Sub
    Protected Sub getWeek()
        ddlWeek.AppendDataBoundItems = True
        ddlWeek.Items.Add(New ListItem("---Tất cả---", 0))
        ddlWeek.DataSource = Enumerable.Range(1, 52)
        ddlWeek.DataBind()
        ' Dim curWeek As Integer = (Now.DayOfYear / 7)
        ddlWeek.SelectedValue = 0 'curWeek
    End Sub
    Protected Function GetFirstDayOfWeek(ByVal year As Integer, ByVal weekNumber As Integer) As DateTime
        Return GetFirstDayOfWeek(year, weekNumber, System.Threading.Thread.CurrentThread.CurrentCulture)
    End Function

    Public Function GetFirstDayOfWeek(ByVal year As Integer, ByVal weekNumber As Integer, ByVal culture As System.Globalization.CultureInfo) As DateTime
        Dim calendar As System.Globalization.Calendar = culture.Calendar
        Dim firstOfYear As New DateTime(year, 1, 1, calendar)
        Dim targetDay As DateTime
        If (firstOfYear.DayOfWeek = DayOfWeek.Monday) Or (firstOfYear.DayOfWeek = DayOfWeek.Sunday) Then
            targetDay = calendar.AddWeeks(firstOfYear, weekNumber - 1)
        Else
            targetDay = calendar.AddWeeks(firstOfYear, weekNumber)
        End If
        Dim firstDayOfWeek As DayOfWeek = culture.DateTimeFormat.FirstDayOfWeek

        While targetDay.DayOfWeek <> firstDayOfWeek
            targetDay = targetDay.AddDays(-1)
        End While

        Return targetDay
    End Function


    Public Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strTitle As String = "", Optional ByVal intType As Integer = 0, Optional ByVal intStatus As Integer = 0, Optional ByVal strCreator As String = "", Optional ByVal intMenu As Integer = 0, Optional ByVal intOriginal As Integer = -1, Optional ByVal strStartCreated As String = "", Optional ByVal intYear As Integer = 0, Optional ByVal intWeek As Integer = 0, Optional ByVal strEndCreated As String = "")
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, _
                                         strTitle, _
                                         intType.ToString, _
                                         intStatus.ToString, _
                                         strCreator, _
                                         intMenu, _
                                         strStartCreated, _
                                         intYear, _
                                         intWeek, _
                                         intOriginal, _
                                         strEndCreated}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim intOrderBy As Int32 = ddlSort.SelectedValue

            Dim startWeek As Date
            If intYear <> 0 And intWeek <> 0 Then
                startWeek = GetFirstDayOfWeek(intYear, intWeek)
            Else
                startWeek = #1/1/1900#
            End If
            Dim p As List(Of uspContentsSelectAll_Result) = data.uspContentsSelectAll(IIf(String.IsNullOrEmpty(txtTitleFilter.Text.Trim) = True, Nothing, txtTitleFilter.Text.Trim), IIf(intType = 0, Nothing, intType), IIf(intStatus = 0, Nothing, intStatus), IIf(String.IsNullOrEmpty(strCreator) = True, Nothing, strCreator), IIf(intMenu = 0, Nothing, intMenu), IIf(String.IsNullOrEmpty(strStartCreated) = True, Nothing, StringToDate(strStartCreated)), IIf(String.IsNullOrEmpty(strEndCreated) = True, Nothing, StringToDate(strEndCreated)), intOriginal, IIf(startWeek = #1/1/1900#, Nothing, startWeek), IIf(startWeek = #1/1/1900#, Nothing, startWeek.AddDays(6)), iPage, intPag_Size, intOrderBy).ToList

            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If
            Dim strKey_Name() As String = {"Id", "Title", "StatusId", "TypeId", "MenuId"}
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If

        End Using

    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        'dang ky async ko postback
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip.ToString), arrSearch(1).ToString, CInt(arrSearch(2).ToString), CInt(arrSearch(3).ToString), arrSearch(4), CInt(arrSearch(5).ToString), CInt(arrSearch(9)), arrSearch(6).ToString, CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(10).ToString)
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(hidCur_Page.Value, arrSearch(1).ToString, CInt(arrSearch(2).ToString), CInt(arrSearch(3).ToString), arrSearch(4), CInt(arrSearch(5).ToString), arrSearch(6).ToString, CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(10).ToString)

    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(hidCur_Page.Value, arrSearch(1).ToString, CInt(arrSearch(2).ToString), CInt(arrSearch(3).ToString), arrSearch(4), CInt(arrSearch(5).ToString), arrSearch(6).ToString, CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(10).ToString)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub cboAction_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboAction.SelectedIndexChanged
        If cboAction.SelectedValue = 1 Then
            Response.Redirect("Create_News.aspx?type=" & cboAction.SelectedValue & "&MenuId=" & Request("MenuId"))
        ElseIf cboAction.SelectedValue = 2 Then
            Response.Redirect("Create_Video.aspx?type=" & cboAction.SelectedValue & "&MenuId=" & Request("MenuId"))
        ElseIf cboAction.SelectedValue = 3 Then
            Response.Redirect("Create_Poll.aspx?type=" & cboAction.SelectedValue & "&MenuId=" & Request("MenuId"))
        ElseIf cboAction.SelectedValue = 4 Then
            Response.Redirect("Create_Image.aspx?type=" & cboAction.SelectedValue & "&MenuId=" & Request("MenuId"))
        ElseIf cboAction.SelectedValue = 5 Then
            Response.Redirect("Create_Tip.aspx?type=" & cboAction.SelectedValue & "&MenuId=" & Request("MenuId"))
        End If
    End Sub
    Protected Sub chkAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        For Each itm As GridViewRow In grdShow.Rows
            Dim chkItem As CheckBox = CType(itm.Cells(0).FindControl("chkItem"), CheckBox)
            If chkItem.Enabled = True Then
                chkItem.Checked = CType(sender, CheckBox).Checked
            End If
        Next
    End Sub
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Dim strQueryString As String = ""
        Dim data As New VSEntities
        intId = grdShow.DataKeys(hidID.Value)("Id").ToString
        Dim q = (From p In data.Contents Where p.Id = intId Select p).FirstOrDefault
        'delete image
        Dim lstImage = (From p In data.Albums Where p.ContensID = intId Select p).ToList
        For Each a In lstImage
            data.Albums.DeleteObject(a)
            data.SaveChanges()
        Next

        'Delete keyword
        Dim obj = (From ck In data.ContentsKeywords Where ck.ContentId = intId Select ck).ToList
        If (Not obj Is Nothing AndAlso obj.Count > 0) Then
            For i As Integer = 0 To obj.Count - 1
                Dim iCid As Integer = obj(i).ContentId
                Dim iKid As Integer = obj(i).KeywordId
                Dim o = (From cok In data.ContentsKeywords Where cok.ContentId = iCid And cok.KeywordId = iKid Select cok).FirstOrDefault
                data.ContentsKeywords.DeleteObject(o)
                Dim h = (From g In data.Keywords Where g.KeywordID = o.KeywordId Select g).FirstOrDefault
                h.Viewed = (IIf(IsNothing(h.Viewed) = True, 0, h.Viewed) - 1)
                data.SaveChanges()
            Next
        End If
        'Delete Subject of contents
        Dim objS = (From s In data.ContentsSubjects Where s.ContentId = intId Select s).FirstOrDefault
        If (Not objS Is Nothing) Then
            data.ContentsSubjects.DeleteObject(objS)
            data.SaveChanges()
        End If

        strLogName = q.Title.ToString
        strQueryString = q.QueryString.ToString
        Try
            data.Contents.DeleteObject(q)
            data.SaveChanges()
            RemoveKeyWordJavascript(strLogName & ";" & strQueryString)
            Insert_App_Log("Delete Contents:" & strLogName & "", Function_Name.Content, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))

            Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()

            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
        End Try
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1).ToString, CInt(arrSearch(2).ToString), CInt(arrSearch(3).ToString), arrSearch(4), CInt(arrSearch(5).ToString), CInt(arrSearch(9)), arrSearch(6).ToString, CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(10).ToString)
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Dim data As New VSEntities
        Dim strLogName As String = ""
        Dim strQueryString As String = ""
        Try
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                    'Delete keyword
                    Dim obj = (From ck In data.ContentsKeywords Where ck.ContentId = intId Select ck).ToList
                    If (Not obj Is Nothing AndAlso obj.Count > 0) Then
                        For i As Integer = 0 To obj.Count - 1
                            Dim iCid As Integer = obj(i).ContentId
                            Dim iKid As Integer = obj(i).KeywordId
                            Dim o = (From cok In data.ContentsKeywords Where cok.ContentId = iCid And cok.KeywordId = iKid Select cok).FirstOrDefault
                            data.ContentsKeywords.DeleteObject(o)
                            Dim h = (From g In data.Keywords Where g.KeywordID = o.KeywordId Select g).FirstOrDefault
                            h.Viewed = (IIf(IsNothing(h.Viewed) = True, 0, h.Viewed) - 1)
                            data.SaveChanges()
                        Next
                    End If
                    'Delete Subject of contents
                    Dim objS = (From s In data.ContentsSubjects Where s.ContentId = intId Select s).FirstOrDefault
                    If (Not objS Is Nothing) Then
                        data.ContentsSubjects.DeleteObject(objS)
                        data.SaveChanges()
                    End If

                    Dim q = (From p In data.Contents Where p.Id = intId Select p).FirstOrDefault
                    strLogName = q.Title.ToString
                    strQueryString = q.QueryString.ToString
                    Try
                        data.Contents.DeleteObject(q)
                        data.SaveChanges()
                        RemoveKeyWordJavascript(strLogName & ";" & strQueryString)
                        Insert_App_Log("Delete Contents:" & strLogName & "", Function_Name.Content, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))

                        intCount += 1
                    Catch ex As Exception
                    End Try
                End If
            Next
            If intCount > 0 Then
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
            Else
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()

            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
        End Try
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1).ToString, CInt(arrSearch(2).ToString), CInt(arrSearch(3).ToString), arrSearch(4), CInt(arrSearch(5).ToString), CInt(arrSearch(9)), arrSearch(6).ToString, CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(10).ToString)
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim status As Integer = grdShow.DataKeys(e.Row.RowIndex)("StatusId")
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)

            Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
            ScriptManager.RegisterAsyncPostBackControl(lnkbtnDelete)

            Dim chkItem As CheckBox = CType(e.Row.FindControl("chkItem"), CheckBox)
            'Permission
            If HasPermission(Function_Name.Content, Session("RoleID"), status, Audit_Type.Delete) = True Then
                lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Else
                lnkbtnDelete.Enabled = False
                chkItem.Enabled = False
            End If

            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            'Permission
            hplEdit.Enabled = HasPermission(Function_Name.Content, Session("RoleID"), status, Audit_Type.Edit)

            Dim hplTitle As HyperLink = CType(e.Row.FindControl("hplTitle"), HyperLink)
            hplTitle.Text = grdShow.DataKeys(e.Row.RowIndex)("Title").ToString
            'Permission
            hplTitle.Enabled = HasPermission(Function_Name.Content, Session("RoleID"), status, Audit_Type.ViewContent)
            Dim lblMenuTile As HyperLink = CType(e.Row.FindControl("lblMenuTile"), HyperLink)
            Using Data As New VSEntities
                Dim MenuId As Integer = grdShow.DataKeys(e.Row.RowIndex)("MenuId")
                Dim q = (From p In Data.Menus Where p.MenuId = MenuId Select p).FirstOrDefault
                If Not q Is Nothing Then
                    lblMenuTile.Text = q.Title.ToString
                    lblMenuTile.NavigateUrl = "../../Page/Contents/List.aspx?MenuId=" & MenuId.ToString
                End If
            End Using

            If CInt(grdShow.DataKeys(e.Row.RowIndex)("TypeId")) = 1 Then
                hplTitle.NavigateUrl = "../../Page/Contents/Detail_News.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                hplEdit.NavigateUrl = "../../Page/Contents/Edit_News.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                '  lblType.Text = "Tin tức"
            ElseIf CInt(grdShow.DataKeys(e.Row.RowIndex)("TypeId")) = 2 Then
                hplTitle.NavigateUrl = "../../Page/Contents/Detail_Video.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                hplEdit.NavigateUrl = "../../Page/Contents/Edit_Video.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                ' lblType.Text = "Video"
            ElseIf CInt(grdShow.DataKeys(e.Row.RowIndex)("TypeId")) = 3 Then
                hplTitle.NavigateUrl = "../../Page/Contents/Detail_Poll.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                hplEdit.NavigateUrl = "../../Page/Contents/Edit_Poll.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                ' lblType.Text = "Bình chọn"
            ElseIf CInt(grdShow.DataKeys(e.Row.RowIndex)("TypeId")) = 4 Then
                hplTitle.NavigateUrl = "../../Page/Contents/Detail_Image.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                hplEdit.NavigateUrl = "../../Page/Contents/Edit_Image.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                '  lblType.Text = "Album ảnh"
            ElseIf CInt(grdShow.DataKeys(e.Row.RowIndex)("TypeId")) = 5 Then
                hplTitle.NavigateUrl = "../../Page/Contents/Detail_Tip.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                hplEdit.NavigateUrl = "../../Page/Contents/Edit_Tip.aspx?status=" & status & "&type=" & grdShow.DataKeys(e.Row.RowIndex)("TypeId") & "&Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                '  lblType.Text = "Tip"
            End If

        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click


        BindToGrid(1, txtTitleFilter.Text.Trim(), drlType.SelectedValue, drlStatus.SelectedValue, txtNguoitao.Text.Trim, drlParent.SelectedValue, ddlSSMOriginal.SelectedValue, txtStartCreated.Text.Trim, ddlYear.SelectedValue, ddlWeek.SelectedValue, txtEndCreated.Text.Trim)

    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1).ToString, CInt(arrSearch(2).ToString), CInt(arrSearch(3).ToString), arrSearch(4), CInt(arrSearch(5).ToString), CInt(arrSearch(9)), arrSearch(6).ToString, CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(10).ToString)
    End Sub
    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        txtTitleFilter.Text = ""
        txtNguoitao.Text = ""
        drlStatus.SelectedValue = 0
        drlType.SelectedValue = 0
        txtStartCreated.Text = ""
        txtEndCreated.Text = ""
        ddlYear.SelectedValue = 0
        ddlWeek.SelectedValue = 0
        ddlSSMOriginal.SelectedValue = -1
        Dim intMenuID As Integer = Integer.TryParse(Request.QueryString("MenuId"), 0)
        drlParent.SelectedValue = intMenuID
        BindToGrid(1, txtTitleFilter.Text.Trim(), drlType.SelectedValue, drlStatus.SelectedValue, txtNguoitao.Text.Trim, drlParent.SelectedValue, ddlSSMOriginal.SelectedValue, txtStartCreated.Text.Trim, ddlYear.SelectedValue, ddlWeek.SelectedValue, txtEndCreated.Text.Trim)
    End Sub
#End Region

    Protected Sub btnChange_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnChange.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Dim data As New VSEntities
        Dim strLogName As String = ""
        Try
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                    Dim q = (From p In data.Contents Where p.Id = intId Select p).FirstOrDefault
                    strLogName = q.Title.ToString
                    Try
                        q.MenuId = BranchNewsId.Value
                        data.SaveChanges()
                        Insert_App_Log("Update Contents:" & strLogName & "", Function_Name.Content, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))

                        intCount += 1
                    Catch ex As Exception
                    End Try
                End If
            Next
            drlParent.SelectedValue = BranchNewsId.Value
            If intCount > 0 Then
                Excute_Javascript("Alertbox('Chuyển dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
            Else
                Excute_Javascript("Alertbox('Chuyển thất bại.');", Me.Page, True)
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()

            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Chuyển thất bại.');", Me.Page, True)
        End Try
        BindToGrid(1, txtTitleFilter.Text.Trim(), drlType.SelectedValue, drlStatus.SelectedValue, txtNguoitao.Text.Trim, BranchNewsId.Value, txtStartCreated.Text.Trim, ddlYear.SelectedValue, ddlWeek.SelectedValue, txtEndCreated.Text.Trim)
    End Sub

    Public Sub Show()
        Dim i As Integer = 0
    End Sub

    Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click

        Dim strCol As String() = {"STT", "Tiêu đề", "Nhánh tin", "Loại", "Ngày tạo", "Người tạo", "Ngày cập nhật cuối", "Người cập nhật cuối", "Trạng thái", "Url", "Lượt xem", "Ngày xuất bản"}
        Using data As New VSEntities
            Dim startWeek As Date = Nothing
            If ddlYear.SelectedValue <> 0 And ddlWeek.SelectedValue <> 0 Then
                startWeek = GetFirstDayOfWeek(ddlYear.SelectedValue, ddlWeek.SelectedValue)
            Else
                startWeek = Nothing
            End If

            Dim EndWeek As Date = Nothing
            If (startWeek = Nothing) Then
                EndWeek = Nothing
            Else
                EndWeek = startWeek.AddDays(6)
            End If

            Dim StartCreateDeate As Date = Nothing
            If String.IsNullOrEmpty(txtStartCreated.Text.Trim) = True Then
                StartCreateDeate = Nothing
            Else
                StartCreateDeate = StringToDate(txtStartCreated.Text.Trim)
            End If

            Dim EndCreateDeate As Date = Nothing
            If String.IsNullOrEmpty(txtEndCreated.Text.Trim) = True Then
                EndCreateDeate = Nothing
            Else
                EndCreateDeate = StringToDate(txtEndCreated.Text.Trim)
            End If

            Dim p As List(Of uspContentsSelectAll_Result) = data.uspContentsSelectAll(IIf(txtTitleFilter.Text.Trim = "", Nothing, txtTitleFilter.Text.Trim) _
                                                                                    , IIf(drlType.SelectedValue = "0", Nothing, CInt(drlType.SelectedValue)) _
                                                                                    , IIf(drlStatus.SelectedValue = "0", Nothing, CInt(drlStatus.SelectedValue)) _
                                                                                    , IIf(txtNguoitao.Text.Trim = "", Nothing, txtNguoitao.Text.Trim) _
                                                                                    , IIf(drlParent.SelectedValue = "0", Nothing, CInt(drlParent.SelectedValue)) _
                                                                                    , IIf(StartCreateDeate = #12:00:00 AM#, Nothing, StartCreateDeate) _
                                                                                    , IIf(EndCreateDeate = #12:00:00 AM#, Nothing, EndCreateDeate) _
                                                                                    , ddlSSMOriginal.SelectedValue _
                                                                                    , IIf(startWeek = #12:00:00 AM#, Nothing, startWeek) _
                                                                                    , IIf(EndWeek = #12:00:00 AM#, Nothing, EndWeek) _
                                                                                    , 1 _
                                                                                    , data.Contents.Count _
                                                                                    , ddlSort.SelectedValue).ToList
            Dim x = p.Select(Function(c) New With {c.RowNum, c.Title, c.TypeId, c.Created, c.Creator, c.Modified, c.Modifier, c.Status, c.Id, c.MenuId, c.QueryString, c.MenuName, c.Viewed, c.PublishedDate}).ToList

            'Export to excel
            Response.ContentType = "application/csv"
            Response.Charset = ""
            Response.AddHeader("Content-Disposition", "attachment;filename=ExportToExcel.xls")
            Response.ContentEncoding = Encoding.Unicode
            Response.BinaryWrite(Encoding.Unicode.GetPreamble())

            Dim sb As StringBuilder = New StringBuilder()

            For i As Integer = 0 To strCol.Length - 1
                sb.Append(strCol(i))
                If (i < strCol.Length - 1) Then
                    sb.Append(vbTab)
                End If
            Next

            Response.Write(sb.ToString() & vbCrLf)
            Response.Flush()

            For i As Integer = 0 To x.Count - 1
                sb = New StringBuilder()
                sb.Append((i + 1).ToString())
                sb.Append(vbTab)
                sb.Append(x(i).Title.ToString().Replace("""", "'").Replace("""", "'"))
                sb.Append(vbTab)
                If (Not x(i).MenuName Is Nothing AndAlso x(i).MenuName.ToString <> "") Then
                    sb.Append(x(i).MenuName.ToString())
                Else
                    sb.Append("")
                End If
                sb.Append(vbTab)
                sb.Append(arrTypeText(x(i).TypeId))
                sb.Append(vbTab)
                sb.Append(x(i).Created.ToString())
                sb.Append(vbTab)

                If (Not x(i).Creator Is Nothing AndAlso x(i).Creator.ToString <> "") Then
                    sb.Append(x(i).Creator.ToString())
                Else
                    sb.Append("")
                End If
                sb.Append(vbTab)
                sb.Append(IIf(IsDBNull(x(i).Modified) = True, "", x(i).Modified.ToString()))
                sb.Append(vbTab)
                If (Not x(i).Modifier Is Nothing AndAlso x(i).Modifier.ToString <> "") Then
                    sb.Append(x(i).Modifier.ToString())
                Else
                    sb.Append("")
                End If
                sb.Append(vbTab)
                sb.Append(x(i).Status.ToString())
                sb.Append(vbTab)
                sb.Append(MainDomain & x(i).MenuId.ToString & "/" & x(i).QueryString.ToString & "-" & x(i).Id.ToString & arrTypeLink(x(i).TypeId) & ".html")
                sb.Append(vbTab)
                sb.Append(IIf(IsNothing(x(i)) = True, 0, x(i).Viewed).ToString())
                sb.Append(vbTab)
                sb.Append(x(i).PublishedDate.ToString())
                Response.Write(sb.ToString() & vbCrLf)
                Response.Flush()
            Next

            Response.End()
        End Using
    End Sub
    Protected Sub btnPublish_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPublish.Click
        Dim StringId As String = ""
        Dim intTotal As Integer
        Using data As New VSEntities
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    StringId += grdShow.DataKeys(item.RowIndex)("Id").ToString & ","
                    'Write Code here
                End If
            Next
            Response.Redirect("../../Page/Contents/ActionList.aspx?Id=" & StringId & "&NStatusId=3")
        End Using
    End Sub

    Protected Sub btnExportToHtml_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportToHtml.Click
        Using data As New VSEntities
            Dim q = (From temp In data.Contents Order By ID Select New With {
                                                                 .QueryString = temp.QueryString, _
                                                                 .Image = temp.Image, _
                                                                 .Contents = temp.Contents, _
                                                                 .Author = temp.Author, _
                                                                 .Id = temp.Id, _
                                                                 .Title = temp.Title, _
                                                                 .Description = temp.Description}).ToList
            'Dim tempabc = q.Count
            Dim folderName As String = Path.Combine(Request.PhysicalApplicationPath, "HtmlContentFolder")
            For Each item As Object In q
                Dim StrQuery As String = ""
                StrQuery = "NoQueryString"
                If Not item.QueryString Is Nothing Then
                    StrQuery = item.QueryString.ToString
                    If StrQuery(0) = "-" Then
                        StrQuery = StrQuery.Remove(0, 1)
                    End If

                    If StrQuery(StrQuery.Length - 1) = "-" Then
                        StrQuery = StrQuery.Remove(StrQuery.Length - 1, 1)
                    End If
                    StrQuery = StrQuery
                End If

                Dim FileName As String = folderName & "\" & StrQuery & "-" & item.Id & ".html"
                'Dim Content = "<h2 class='title'>" & item.Title & "</h2>"
                'Content += "<p class='image'><img src='" + MainDomain & item.Image + "'/></p>"
                'Content += "<p class='description'>" & item.Description & "</p>"
                'Content += "<p class='contents'>" & item.Contents & "</p>"
                'Content += "<p class='author'> Tác giả : " & item.Author & "</p>"
                Dim w As StreamWriter = File.CreateText(FileName)
                w.WriteLine("<html>")
                w.WriteLine("<head>")
                w.WriteLine("<title>")
                w.Write(item.Title)
                w.WriteLine("</title>")
                w.WriteLine("</head>")
                w.WriteLine("<body>")
                w.WriteLine("<h2 class='title'>" & item.Title & "</h2>")
                w.WriteLine("<p class='image'><img src='" + MainDomain & item.Image + "'/></p>")
                w.WriteLine("<p class='description'>" & item.Description & "</p>")
                w.WriteLine("<p class='contents'>" & item.Contents & "</p>")
                w.WriteLine("<p class='author'> Tác giả : " & item.Author & "</p>")
                w.WriteLine("</body>")
                w.WriteLine("</html>")
                w.Close()
            Next
        End Using
    End Sub
End Class
